package com.omesoft.hksnore.monitoring;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.omesoft.hksnore.R;
import com.omesoft.hksnore.util.CustomToast;
import com.omesoft.hksnore.util.dao.MendaleSleepAllIfcImpl;
import com.omesoft.hksnore.util.data.MySharedPreferencesUtil;
import com.omesoft.hksnore.util.entity.Medix_Pub_Sync_Sleep;
import com.omesoft.hksnore.util.omeview.MyViewPager;

import java.util.ArrayList;

/**
 * Created by Omesoft on 2017/3/13.
 */

public class MonitorCalendarSelectActivity extends FragmentActivity implements View.OnClickListener {

    private String tag = "MonitorCalendarActivity";

    public static final int HANDLER_SET_VIEWPAGER_HEIGHT = 0x01;
    public static final int HANDLER_SET_CALENDAR_MONTH = 0x02;
    public static final int HANDLER_FINISH = 0x03;// 用户已选择某个日期
    public static final int HANDLER_VISBLE = 0x04;

    private Context context;
    // private Config config;
    private TextView title;
    private ImageView image_pre, image_next, image_close;
    private MyViewPager pager;
    private MyPagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragmentList;
    private Handler handler;

    private MendaleSleepAllIfcImpl ifc;

    public static int selectedIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.snore_activity_monitor_calendar_select);
        initHandler();
        init();
        initView();
        loadView();
    }

    @Override
    public void finish() {
        // TODO Auto-generated method stub
        super.finish();
        overridePendingTransition(R.anim.monitor_calendarselect_enter, R.anim.monitor_calendarselect_exit);
        // overridePendingTransition(0, 0);
        CalendarSelectFragment.selectDate = null;
    }

    protected void init() {
        // TODO Auto-generated method stub
        context = this;
        // config = (Config) this.getApplicationContext();
        String month = null;
        try {
            if (getIntent() != null) {
                month = getIntent().getExtras().getString("month");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v(tag, "month::" + month);
        ifc = new MendaleSleepAllIfcImpl(context);
        fragmentList = new ArrayList<Fragment>();
        // fragmentList.add(new CalendarSelectFragment(null, null));
        if (ifc.findTotal(MySharedPreferencesUtil.getMemberId(context)) > 0) {
            ArrayList<Medix_Pub_Sync_Sleep> dtos;
            dtos = ifc.findDateTimeASC(MySharedPreferencesUtil.getMemberId(context));
            int size = dtos.size();
            Log.e(tag, "size::" + size);
            for (int i = 0; i < size; i++) {
                String date = dtos.get(i).getCreatedDate();
                Log.e(tag, "date::" + date);
                if (month != null && month.equals(date))
                    selectedIndex = i;
                CalendarSelectFragment fragment = new CalendarSelectFragment(dtos.get(i).getCreatedDate(), handler);
                fragmentList.add(fragment);
            }
        } else {
            Log.v(tag, "size::0");
            Time time = new Time();
            time.setToNow();
            String date = time.format("%Y-%m-%d");
            CalendarSelectFragment fragment = new CalendarSelectFragment(date, handler);
            fragmentList.add(fragment);
        }
        Log.v(tag, "selectedIndex  " + selectedIndex);
        Log.v(tag, "fragmentList.size()  " + fragmentList.size());
    }

    protected void initView() {
        // TODO Auto-generated method stub
        title = (TextView) findViewById(R.id.activity_monitor_calendar_title);
        pager = (MyViewPager) findViewById(R.id.activity_monitor_calendar_viewpager);
        image_pre = (ImageView) findViewById(R.id.activity_monitor_calendar_pre);
        image_next = (ImageView) findViewById(R.id.activity_monitor_calendar_next);
        image_close = (ImageView) findViewById(R.id.activity_monitor_calendar_close);
    }

    @SuppressWarnings("deprecation")
    protected void loadView() {
        // TODO Auto-generated method stub
        image_pre.setOnClickListener(this);
        image_next.setOnClickListener(this);
        image_close.setOnClickListener(this);
        pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(pagerAdapter);
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                Log.v(tag, "onPageSelected");
                selectedIndex = arg0;
                CalendarSelectFragment fragment = (CalendarSelectFragment) fragmentList.get(arg0);
                Message msg1 = Message.obtain();
                msg1.what = HANDLER_VISBLE;
                msg1.obj = fragment.getGridViewHeight();
                handler.sendMessage(msg1);
                title.setText(fragment.getTitle());
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        Log.v(tag, "hasFocus " + hasFocus);
        if (hasFocus) {
            Log.v(tag, "fragmentList.size() " + fragmentList.size());
            pager.setCurrentItem(selectedIndex);
            CalendarSelectFragment fragment = (CalendarSelectFragment) fragmentList.get(selectedIndex);
            Message msg1 = Message.obtain();
            msg1.what = HANDLER_VISBLE;
            msg1.obj = fragment.getGridViewHeight();
            title.setText(fragment.getTitle());
            handler.sendMessage(msg1);
        }
        super.onWindowFocusChanged(hasFocus);
    }

    protected void initHandler() {
        // TODO Auto-generated method stub
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                switch (msg.what) {
                    case HANDLER_SET_VIEWPAGER_HEIGHT:
                        int height = (Integer) msg.obj;
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) pager.getLayoutParams();
                        params.height = height;
                        pager.setLayoutParams(params);
                        pager.setVisibility(View.VISIBLE);
                        break;
                    case HANDLER_SET_CALENDAR_MONTH:
                        String str = (String) msg.obj;
                        title.setText(str);
                        break;
                    case HANDLER_FINISH:
                        String date = (String) msg.obj;
                        Log.v("CalendarResult", "date::" + date);
                        Intent intent = new Intent();
                        intent.putExtra("CalendarResult", date);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                        break;

                    case HANDLER_VISBLE:
                        int height2 = (Integer) msg.obj;
                        LinearLayout.LayoutParams params2 = (LinearLayout.LayoutParams) pager.getLayoutParams();
                        params2.height = height2;
                        pager.setLayoutParams(params2);
                        pager.setVisibility(View.VISIBLE);

                        break;
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.activity_monitor_calendar_pre:
                if (selectedIndex > 0) {
                    selectedIndex--;
                    pager.setCurrentItem(selectedIndex);
                } else {
                    CustomToast.showToasts(context, R.string.monitor_calendar_select_nodata);

                }
                break;
            case R.id.activity_monitor_calendar_next:
                if (selectedIndex < fragmentList.size() - 1) {
                    selectedIndex++;
                    pager.setCurrentItem(selectedIndex);
                } else
                    CustomToast.showToasts(context, R.string.monitor_calendar_select_nodata);

                break;
            case R.id.activity_monitor_calendar_close:
                finish();
                break;
        }
    }

    private class MyPagerAdapter extends FragmentStatePagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fragmentList.get(arg0);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

    }
}
